package com.hksj.jetlinks.handler;

import com.alibaba.fastjson.JSON;
import com.hksj.common.core.model.Rest;
import com.hksj.common.core.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component//认证过程中出现的异常
public class AuthenticationExceptionHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        //Result result = new Result(HttpStatus.UNAUTHORIZED.value(), "认证失败请重新登录");
        String message = "认证失败,请重新登录";

        if (authException instanceof LockedException){
            message = "用户被锁定";
        }
        if (authException instanceof DisabledException){
            message = "用户已禁用,请联系管理员";
        }
        if (authException instanceof CredentialsExpiredException){
            message = "token过期,请重新登录";
        }
        if (authException instanceof AccountExpiredException){
            message = "用户账号已过期";
        }
        if (authException instanceof BadCredentialsException){
            message = "用户名或密码错误,请重新登录";
        }
        Rest result = Rest.fail(HttpStatus.UNAUTHORIZED.value(), message);
        String json = JSON.toJSONString(result);
        WebUtils.renderString(response,json);
    }
}
